//在排序数组中查找元素的第一个和最后一个位置
//测试链接 https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/
public class SearchRange {
    public int[] searchRange(int[] nums, int target) {
        int[] ret = {-1,-1};
        //特殊情况
        if (nums.length == 0){
            return ret;
        }

        int left = 0, right = nums.length-1;
        //找左端点
        while(left < right){
            int mid = left + (right-left)/2; //对于偶数的区间，中点为靠左的位置
            if(nums[mid] < target){
                left = mid + 1;
            }else{
                right = mid;
            }
        }
        if(nums[right] != target){
            return new int[]{-1,-1};
        }
        ret[0] = left;
        //找右端点
        right = nums.length-1;
        while(left < right){
            int mid = left + (right - left + 1)/2; //对于偶数的区间，中点为靠右的位置
            if(nums[mid] <= target){
                left = mid;
            }else{
                right = mid - 1;
            }
        }
        ret[1] = left;

        return ret;
    }
}
